package cn.hl.hm.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * xianghan 2017-11-6 17:44:02
 */
public class ContextHolderUtils {

	/**
	 * SpringMvc下获取request
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		HttpServletRequest request = null;
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (servletRequestAttributes != null) {
			request = servletRequestAttributes.getRequest();
		}
		return request;

	}
	/**
	 * SpringMvc下获取session
	 * 
	 * @return
	 */
	public static HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		return session;

	}
	
	/**
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public String findCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		Cookie cookie = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (cookie.getName().equals(name)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	public void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		Cookie cookies[] = request.getCookies();
		Cookie cookie = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (cookie.getName().equalsIgnoreCase(name)) {
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		}
	}

	public static String getParam(HttpServletRequest request, String key){
		try{
			Object obj=request.getAttribute(key);
			if(obj==null){
				return "";
			}else{
				return new String(obj.toString().getBytes("iso-8859-1"),"UTF-8");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getBasePath(HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath("/");// 服务器路径
	}
	
	
}

